<?php

namespace app\admin\controller\kuerp;

use addons\kuerp\model\OperationLog;
use addons\kuerp\model\Record;
use app\common\controller\Backend;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use think\Log;

/**
 * 客户联系人
 *
 * @icon fa fa-circle-o
 */
class CustomersUser extends Backend
{

    /**
     * CustomersUser模型对象
     * @var \app\admin\model\kuerp\CustomersUser
     */
    protected $model = null;
    protected $selectpageFields = "id,first_connect_name,first_connect_mobile";
    protected $searchFields = 'first_connect_name,first_connect_mobile';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuerp\CustomersUser;
        $this->view->assign("isFirstList", $this->model->getIsFirstList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);
        $this->assignconfig('hasExportPermission', $this->auth->check($setData['nowmenu'].'/export') == 1);//是否有导出权限
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $ruleWhere = [];
            $type = $this->request->get('type');//1仅本人
            if (!$this->auth->isSuperAdmin()) {
                $where1 = [];
                if ($this->auth->is_sale) {
                    $where1 = ['staff_member_id' => $this->auth->staff_member_id];
                    $ruleWhere['staff_member_id'] = ['exp', Db::raw(' in (0, '.$this->auth->staff_member_id.')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                }
                //部门经理查看部门成员 上级部门能查看下级部门
                $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
                $sale_users = [];
                //转为职员id
                if ($adminids) {
                    $sale_users = (new StaffMember())->getStaffMemberIds($adminids);
                }
                if ($sale_users) {
                    $where1 = ['staff_member_id' => ['in', $sale_users]];
                    $ruleWhere['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                } else {
                    $where1 = ['staff_member_id' => -1];
                    $ruleWhere['staff_member_id'] = ['exp', Db::raw(' =-1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                }
                if ($type == 1) {
                    $ruleWhere['staff_member_id'] = $where1['staff_member_id'];
                }
            }
            
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['customers'])
                    ->where($where)
                    ->where($ruleWhere)
                    ->order($sort, $order)
                    // ->order('customers.staff_member_id asc, id desc')
                    ->paginate($limit);
            // echo $this->model->getLastSql();
            foreach ($list as $row) {
                
                $row->getRelation('customers')->visible(['customer_name', 'sale_user']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        //获取客户customers_code
        $customerinfo = Db::name('kuerp_customers')->where('id', $params['sid'])->find();
        if (empty($customerinfo)) {
            $this->error('客户信息不存在');
        }
        $params['customers_code'] = $customerinfo['customer_code'];
        $mobile = $params['first_connect_mobile']??'';
        if (preg_match('/^1\d{10}$/', $mobile) ==false) {
            $this->error('手机号格式错误');
        }
        if ($this->model->where([
            'sid'=>$params['sid'],
            'first_connect_mobile' => $mobile,
        ])->find()) {
            $this->error('联系人手机号已存在');
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //判断是否首要联系人
            if ($params['is_first'] == 1) {
                //将其他首要联系人改为非首要
                $this->model->where('sid', $params['sid'])->update(['is_first' => 0]);
                $update_customer = [
                    'connet_name' => $params['first_connect_name'],
                    'customer_mobile' => $params['first_connect_mobile'],
                    'customer_phone' => $params['first_connect_phone'],
                    'qq_wx_email' => $params['qq_wx_email'],
                    'getgoods_address' => $params['connect_address'],
                ];
                $res = \app\admin\model\kuerp\Customers::update($update_customer, ['id' => $params['sid']]);
                if (false === $res) {
                    // 验证失败 输出错误信息
                    throw new Exception('新增失败');
                }
            }
            $result = $this->model->allowField(true)->save($params);
            //创建日志
            OperationLog::createLog(OperationLog::CONTACTS_TYPE,$this->model->id, '创建联系人');
            //新增跟进记录
            Record::quickCreateRecord(Record::CUSTOMER_TYPE, $params['sid'], '新增联系人：' . $params['first_connect_name']);
            OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $params['sid'], '新增联系人：' . $params['first_connect_name']);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        //获取客户customers_code
        $customerinfo = Db::name('kuerp_customers')->where('id', $params['sid'])->find();
        if (empty($customerinfo)) {
            $this->error('客户信息不存在');
        }
        $params['customers_code'] = $customerinfo['customer_code'];
        $mobile = $params['first_connect_mobile']??'';
        if (preg_match('/^1\d{10}$/', $mobile) ==false) {
            $this->error('手机号格式错误');
        }
        if ($this->model->where([
            'id'  => ['neq', $ids],
            'sid' =>$params['sid'],
            'first_connect_mobile' => $mobile,
        ])->find()) {
            $this->error('联系人手机号已存在');
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //判断是否首要联系人
            if ($params['is_first'] == 1) {
                //将其他首要联系人改为非首要
                $this->model->where('sid', $params['sid'])->update(['is_first' => 0]);
                $update_customer = [
                    'connet_name' => $params['first_connect_name'],
                    'customer_mobile' => $params['first_connect_mobile'],
                    'customer_phone' => $params['first_connect_phone'],
                    'qq_wx_email' => $params['qq_wx_email'],
                    'getgoods_address' => $params['connect_address'],
                ];
                $res = \app\admin\model\kuerp\Customers::update($update_customer, ['id' => $params['sid']]);
                if (false === $res) {
                    // 验证失败 输出错误信息
                    throw new Exception('编辑失败');
                }
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function import()
    {
        if ($this->request->isPost()){
            set_time_limit(0);
            ini_set('memory_limit', '512M');
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            $editstatus = isset($_POST['editstatus'])?$_POST['editstatus']:1;//是否需要更新
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                if ($importHeadType == 'comment') {
                    $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                } else {
                    $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                }
            }
            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $row1 = (string)$currentSheet->getCellByColumnAndRow(1, 1)->getValue();
                $titleRow = $row1 == '联系人信息' ? 2 : 1;//标题按当前系统在第二行，其他系统导过来在第一行
                $fields = [];
                for ($currentRow = $titleRow; $currentRow <= $titleRow; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = str_replace('*','',$val);
                        $fields[] = (string)trim($val);
                    }
                }

                for ($currentRow = $titleRow+1; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : trim($val);
                    }
                    $row = array_combine($fields, $values);
                    
                    $row['客户名称'] = !empty($row['对应客户']) ? $row['对应客户'] : ($row['客户名称'] ?? '');
                    $row['联系人'] = !empty($row['姓名']) ? $row['姓名'] : ($row['联系人'] ?? '');
                    $row['职务'] = !empty($row['职务']) ? $row['职务'] : ($row['职务'] ?? '');
                    $row['手机'] = !empty($row['手机']) ? $row['手机'] : ($row['手机'] ?? '');
                    $row['首要联系人'] = $row['首要联系人'] ?? '';
                    if(empty($row['客户名称']) || empty($row['联系人'])){
                        $this->error('客户名称或联系人必填');
                    }
                    $insert[] = $row;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $customernames = array_unique(array_column($insert,'客户名称'));
            Db::execute("SET SESSION group_concat_max_len = 1048576");
            $customerlist = Db::name('kuerp_customers')->where(['customer_name'=>['in',$customernames]])->field('customer_name,GROUP_CONCAT(customer_code) as customer_codes,GROUP_CONCAT(id) as ids')->group('customer_name')->select();
            $customerlist = $customerlist ? array_column($customerlist,null,'customer_name') : [];
            if (count($customernames) != count($customerlist)) {
                // $this->error('客户【'.implode(',',array_diff($customernames,array_keys($customerlist))).'】不存在，导入失败');
            }
            
            $adduserlist = [];
            $updateuserlist = [];
            $noexists = [];
            foreach ($insert as $insert_k=>$insert_v){
                $customer_codes = $customerlist[$insert_v['客户名称']]['customer_codes'] ?? '';
                //获取客户id
                $customerids = $customerlist[$insert_v['客户名称']]['ids'] ?? '';
                if (empty($customerids)) {
                    $noexists[] = $insert_v['客户名称'];
                    continue;
                    // $this->error('客户【'.$insert_v['客户名称'].'】不存在，导入失败');
                }
                
                $dbuserlist = [];
                if ($editstatus) {
                    //获取同名称联系人
                    $dbuserlist = Db::name('kuerp_customers_user')->where(['sid'=>['in',$customerids],'first_connect_name'=>$insert_v['联系人']])->column('id,first_connect_phone,qq_wx_email,connect_address', 'sid');
                }
                $customeridsarr = explode(',', $customerids);
                $customer_codesarr = explode(',', $customer_codes);
                foreach ($customeridsarr as $ids_k=>$ids_v) {
                    if (!empty($dbuserlist[$ids_v])){
                        if ($editstatus) {
                            $updateuserlist[] = [
                                'id'=>$dbuserlist[$ids_v]['id'],
                                'first_connect_name'=>$insert_v['联系人'],
                                'first_connect_mobile'=>$insert_v['手机'],
                                'job'=>$insert_v['职务'],
                                'first_connect_phone'=>$insert_v['座机'] ?? $dbuserlist[$ids_v]['first_connect_phone'],
                                'qq_wx_email'=>$insert_v['QQ/微信'] ?? $dbuserlist[$ids_v]['qq_wx_email'],
                                'connect_address'=>$insert_v['联系地址'] ?? $dbuserlist[$ids_v]['connect_address'],
                                'updatetime'  => time(),
                                // 'is_first'=>!empty($insert_v['首要联系人']) && $insert_v['首要联系人'] == '是' ? 1 : 0,
                            ];
                        }
                    } else {
                        $adduserlist[] = [
                            'customers_code'=>$customer_codesarr[$ids_k],
                            'sid'=>$ids_v,
                            'first_connect_name'=>$insert_v['联系人'],
                            'first_connect_mobile'=>$insert_v['手机'],
                            'job'=>$insert_v['职务'],
                            'first_connect_phone'=>$insert_v['座机'] ?? '',
                            'qq_wx_email'=>$insert_v['QQ/微信'] ?? '',
                            'connect_address'=>$insert_v['联系地址'] ?? '',
                            'createtime'            => time(),
                            'updatetime'            => time(),
                            // 'is_first'=>!empty($insert_v['首要联系人']) && $insert_v['首要联系人'] == '是' ? 1 : 0,
                        ];
                    }
                    
                }
            }
            $noexists = array_unique($noexists);
            $chunkSize = 200; // 每次插入的数据条数
            Db::startTrans();
            try {
                if(!empty($updateuserlist)){
                    $dataChunks = array_chunk($updateuserlist, $chunkSize); // 将数据分割成小数组
                    foreach ($dataChunks as $chunk) {
                        $res = $this->model->saveAll($chunk);
                    }
                    // $res = $this->model->saveAll($updateuserlist);
                }
                if(!empty($adduserlist)){
                    $dataChunks = array_chunk($adduserlist, $chunkSize); // 将数据分割成小数组
                    foreach ($dataChunks as $chunk) {
                        $res = $this->model->saveAll($chunk);
                    }
                    // $res = $this->model->saveAll($adduserlist);
                }
                if ($noexists) {
                    Log::write('客户【'.implode(',',$noexists).'】不存在，文件名称：'.$file.'，导入失败');
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success(['update'=>count($updateuserlist),'add'=>count($adduserlist), 'noexists'=>implode(',',$noexists)]);
        }
        $this->assign('time', time());
        return $this->view->fetch();
    }


}
